<?php
namespace app\modules\controllers;
use Yii;
use app\models\User;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Profile;

class UserController extends Controller
{
    //用户列表
    public function actionUserlist()
    {
        $this->layout='adminlist.php';
        $model= User::find()->joinWith('profile');//关联查询
        $count=$model->count();
        $pageSize= \Yii::$app->params['pageSize']['manage'];//从配置文件中获取
        $pager=new Pagination(['totalCount'=>$count,'pageSize'=>$pageSize]);
        $userlist=$model->offset($pager->offset)->limit($pager->limit)->all();
//        var_dump($userlist[0]->profile);exit;
        return $this->render('userlist',['userlist'=>$userlist,'pager'=>$pager]);
    }
    
    public function actionUseradd()
    {
        $this->layout='adminlist.php';
        $model=new User();
        if(\Yii::$app->request->isPost)
        {
            $post= \Yii::$app->request->post();
            if($model->reg($post)){
                \Yii::$app->session->setFlash('info','添加成功');
            }else{
                \Yii::$app->session->setFlash('info','添加失败');
            }
        }
        $model->userpass="";
        $model->respass="";
        return $this->render('useradd',['model'=>$model]);
    }
    
    //删除时，先删除profile表，再删除user表，用事务处理
    public function actionDel()
    {
        $userid= \Yii::$app->request->get('userid');
        if(empty($userid)){
            $this->redirect(['user/userlist']);
        }
        try{
        $trans= Yii::$app->db->beginTransaction();
        if($obj=Profile::find()->where('userid=:id',[':id'=>$userid])->one()){
            $res= Profile::deleteAll('userid=:id',[':id'=>$userid]);
            if(empty($res)){
                throw new Exception();
            }
        }
        if(!User::deleteAll('userid=:id',[':id'=>$userid])){
            throw new Exception();
        }
        $trans->commit();
        \Yii::$app->session->setFlash('info','删除成功');
       } catch (\yii\db\Exception $e){
           if(Yii::$app->db->getTransaction()){
               $trans->rollBack();
           }
       }
       $this->redirect(['user/userlist']);
    }
    
    //用户个人信息
    public function actionUserinfo()
    {
        $this->layout="adminlist.php";
        return $this->render('userinfo');
    }
}
